#include "service_impl.h"
#include "tools.h"
#include "department.h"
#include "servicedao_file_impl.h"
using namespace std;
using namespace MAN;

ServiceImpl::ServiceImpl()
{
	init_id(DeptId_PATH,1001);
	init_id(EmpID_PATH,2001);
	m_pDao = new ServiceDaoFileImpl;
	m_pDao->load(m_vecDepts);
}

//增加部门 
bool ServiceImpl::addDept(Department& dept)
{
	for( unsigned int i =0; i < m_vecDepts.size(); i++ )
	{
		if( strcmp(dept.m_strName,m_vecDepts[i].m_strName) == 0)
		{			
			return false;
		}
	}
	m_vecDepts.push_back(dept);
	return true;
}

//删除部门 
bool ServiceImpl::deleteDept(int deptid)
{
	for( unsigned int i =0; i < m_vecDepts.size(); i++ )
	{
		if( deptid == m_vecDepts[i].m_nId)
		{
			m_vecDepts.erase(m_vecDepts.begin()+i);
			return true;
		}
	}
	return false;
}

//列出部门
vector<Department>& ServiceImpl::listDept(void)
{
	return m_vecDepts;
}

//增加员工
bool ServiceImpl::addEmp(Employee emp,int depid)
{	
	for(unsigned int i = 0; i < m_vecDepts.size();i++)
	{
		if(depid == m_vecDepts[i].m_nId)
		{
			m_vecDepts[i].m_vecEmps.push_back(emp);
			return true;
		}
	}
	
	return false;
}

//删除员工
bool ServiceImpl::deleteEmp(int depid,int empid)
{
	for(unsigned int i = 0; i < m_vecDepts.size();i++)
	{
		if(depid == m_vecDepts[i].m_nId)
		{		
			for(unsigned int j = 0; j< m_vecDepts[i].m_vecEmps.size();j++)
			{
				if(m_vecDepts[i].m_vecEmps[j].m_nId == empid)
				{
					m_vecDepts[i].m_vecEmps.erase(m_vecDepts[i].m_vecEmps.begin()+j);
					return true;
				}
			}
			
		}		
	}
	return false;
}

//修改员工信息 
bool ServiceImpl::modifyEmp(Employee emp,int depid)
{	
	
	for(unsigned int i = 0; i < m_vecDepts.size();i++)
	{
		if(depid == m_vecDepts[i].m_nId)
		{
			for(unsigned int j = 0; j< m_vecDepts[i].m_vecEmps.size();j++)
			{
				if( m_vecDepts[i].m_vecEmps[j].m_nId == emp.m_nId )
				{
					m_vecDepts[i].m_vecEmps[j].m_nId = emp.m_nId;
					strcpy(m_vecDepts[i].m_vecEmps[j].m_strName,emp.m_strName);
					m_vecDepts[i].m_vecEmps[j].m_bGender = emp.m_bGender;
					m_vecDepts[i].m_vecEmps[j].m_nAge = emp.m_nAge;
					return true;
				}
			}
			
		}
	}
	return false;
}

//列出部门员工 
vector<Employee>& ServiceImpl::listEmp(int deptid)
{
	unsigned int i = 0;
	for( ; i < m_vecDepts.size();i++ )
	{
		if(m_vecDepts[i].m_nId == deptid)
		{
			break;
		}
	}
	return m_vecDepts[i].m_vecEmps;
}

//列出所有员工 
vector<Employee>& ServiceImpl::listAllEmp(void )
{
	static vector<Employee> temp_all;
	temp_all.clear();
	for( unsigned int i = 0; i < m_vecDepts.size(); i++ )
	{
		for(unsigned int j =0; j < m_vecDepts[i].m_vecEmps.size(); j++)
		{
			temp_all.push_back(m_vecDepts[i].m_vecEmps[j]);
		}
	}
	return temp_all;
}

ServiceImpl::~ServiceImpl()
{
	m_pDao->save(m_vecDepts);
	delete m_pDao;
}